
<template>
    <div>
        <div class="card">
            <Toolbar class="mb-4">
                <template #start>
                    <Button label="新增" icon="pi pi-plus" severity="success" class="mr-2" @click="openNew" />
                    <Button label="删除" icon="pi pi-trash" severity="danger" @click="confirmDeleteSelected"
                        :disabled="!selectedProducts || !selectedProducts.length" />
                </template>

                <template #end>
                    <!-- <FileUpload mode="basic" accept="image/*" :maxFileSize="1000000" label="Import" chooseLabel="Import"
                        class="mr-2 inline-block" /> -->
                    <Button label="导出" icon="pi pi-upload" severity="help" @click="exportCSV($event)" />
                </template>
            </Toolbar>

            <DataTable ref="dt" :value="products" v-model:selection="selectedProducts" dataKey="id" :paginator="true"
                :rows="10" :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 25]"
                currentPageReportTemplate="Showing {first} to {last} of {totalRecords} products">
                <template #header>
                    <div class="flex flex-wrap gap-2 align-items-center justify-content-between">
                        <h4 class="m-0">商品详情</h4>
                        <span class="p-input-icon-left">
                            <i class="pi pi-search" />
                            <InputText v-model="filters['global'].value" placeholder="Search..." />
                        </span>
                    </div>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <!-- <Column field="code" header="Code" sortable style="min-width:12rem"></Column> -->
                <Column field="name" header="名称" sortable style="min-width:16rem"></Column>
                <Column header="图片">
                    <template #body="slotProps">
                        <img :src="`${slotProps.data.image}`" :alt="slotProps.data.image" class="border-round"
                            style="width: 64px" />
                    </template>
                </Column>
                <Column field="price" header="定价" sortable style="min-width:8rem">
                    <template #body="slotProps">
                        {{ formatCurrency(slotProps.data.price) }}
                    </template>
                </Column>
                <Column field="category" header="类别" sortable style="min-width:10rem"></Column>
                <Column field="rating" header="热度" sortable style="min-width:12rem">
                    <template #body="slotProps">
                        <Rating :modelValue="slotProps.data.rating" :readonly="true" :cancel="false" />
                    </template>
                </Column>
                <Column field="quantity" header="数量" sortable style="min-width:12rem"></Column>
                <!-- <Column field="inventoryStatus" header="Status" sortable style="min-width:12rem">
                    <template #body="slotProps">
                        <Tag :value="slotProps.data.inventoryStatus" :severity="getStatusLabel(slotProps.data.inventoryStatus)" />
                    </template>
                </Column> -->
                <Column :exportable="false" style="min-width:8rem">
                    <template #body="slotProps">
                        <Button icon="pi pi-pencil" outlined rounded class="mr-2" @click="editProduct(slotProps.data)" />
                        <Button icon="pi pi-trash" outlined rounded severity="danger"
                            @click="confirmDeleteProduct(slotProps.data)" />
                    </template>
                </Column>
            </DataTable>
        </div>

        <Dialog v-model:visible="productDialog" :style="{ width: '450px' }" header="Product Details" :modal="true"
            class="p-fluid">
            <img v-if="product.image" :src="`${product.image}`" :alt="product.image" class="block m-auto pb-3"
                style="width: 200px;" />
            <FileUpload :name="imageName" url="/api/productImage" @upload="upload($event)"
                :multiple="true" accept="image/*" :maxFileSize="1000000">
                <template #empty>
                    <p>Drag and drop files to here to upload.</p>
                </template>
            </FileUpload>
            <div class="field">
                <label for="name">Name</label>
                <InputText id="name" v-model.trim="product.name" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !product.name }" />
                <small class="p-error" v-if="submitted && !product.name">Name is required.</small>
            </div>
            <!-- <div class="field">
                <label for="description">Description</label>
                <Textarea id="description" v-model="product.description" required="true" rows="3" cols="20" />
            </div> -->

            <!-- <div class="field">
				<label for="inventoryStatus" class="mb-3">Inventory Status</label>
				<Dropdown id="inventoryStatus" v-model="product.inventoryStatus" :options="statuses" optionLabel="label" placeholder="Select a Status">
					<template #value="slotProps">
						<div v-if="slotProps.value && slotProps.value.value">
                            <Tag :value="slotProps.value.value" :severity="getStatusLabel(slotProps.value.label)" />
                        </div>
                        <div v-else-if="slotProps.value && !slotProps.value.value">
                            <Tag :value="slotProps.value" :severity="getStatusLabel(slotProps.value)" />
                        </div>
						<span v-else>
							{{slotProps.placeholder}}
						</span>
					</template>
				</Dropdown>
			</div> -->

            <div class="field">
                <label class="mb-3">Category</label>
                <div class="formgrid grid">
                    <div class="field-radiobutton col-6">
                        <RadioButton id="category1" name="category" value="Games" v-model="product.category" />
                        <label for="category1">Games</label>
                    </div>
                    <div class="field-radiobutton col-6">
                        <RadioButton id="category2" name="category" value="Device" v-model="product.category" />
                        <label for="category2">Device</label>
                    </div>
                </div>
                <small class="p-error" v-if="submitted && !product.category">Name is required.</small>
            </div>

            <div class="formgrid grid">
                <div class="field col">
                    <label for="price">Price</label>
                    <InputNumber id="price" v-model="product.price" mode="currency" currency="CNY" locale="cn-CN"
                        :class="{ 'p-invalid': submitted && !product.price }" />
                    <small class="p-error" v-if="submitted && !product.price">Name is required.</small>

                </div>
                <div class="field col">
                    <label for="quantity">Quantity</label>
                    <InputNumber id="quantity" v-model="product.quantity" integeronly
                        :class="{ 'p-invalid': submitted && !product.quantity }" />
                    <small class="p-error" v-if="submitted && !product.quantity">Name is required.</small>

                </div>
            </div>
            <template #footer>
                <Button label="Cancel" icon="pi pi-times" text @click="hideDialog" />
                <Button label="Save" icon="pi pi-check" text @click="saveProduct" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteProductDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
            <div class="confirmation-content">
                <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
                <span v-if="product">Are you sure you want to delete <b>{{ product.name }}</b>?</span>
            </div>
            <template #footer>
                <Button label="No" icon="pi pi-times" text @click="deleteProductDialog = false" />
                <Button label="Yes" icon="pi pi-check" text @click="deleteProduct" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteProductsDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
            <div class="confirmation-content">
                <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
                <span v-if="product">Are you sure you want to delete the selected products?</span>
            </div>
            <template #footer>
                <Button label="No" icon="pi pi-times" text @click="deleteProductsDialog = false" />
                <Button label="Yes" icon="pi pi-check" text @click="deleteSelectedProducts" />
            </template>
        </Dialog>
        <Toast />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { FilterMatchMode } from 'primevue/api';
import { useToast } from 'primevue/usetoast';
import axios from '../../util/interceptor';
import Toast from 'primevue/toast';

onMounted(() => {
    getData();
    console.log(products)
});

const imageName = ref("");
const toast = useToast();
const dt = ref();
const products = ref();
const productDialog = ref(false);
const deleteProductDialog = ref(false);
const deleteProductsDialog = ref(false);
const product = ref({});
const selectedProducts = ref();
const filters = ref({
    'global': { value: null, matchMode: FilterMatchMode.CONTAINS },
});
const submitted = ref(false);
const statuses = ref([
    { label: 'INSTOCK', value: 'instock' },
    { label: 'LOWSTOCK', value: 'lowstock' },
    { label: 'OUTOFSTOCK', value: 'outofstock' }
]);

const upload = (event) => {
    console.log(event.files[0].name.substring(event.files[0].name.lastIndexOf(".")));
    console.log(!product.value.id)
    if (!product.value.id) {
        product.value["image"] = "demo/images/product/" + imageName.value + event.files[0].name.substring(event.files[0].name.lastIndexOf("."));
    }
    if (event.xhr.status == 200) {
        toast.add({ severity: 'success', summary: 'Success', detail: "图片更改成功", life: 3000 });
        /* setTimeout(() => {
            location.reload();
        }, 2000); */
    }
    getData();
};

const getData = async () => {
    const response = await axios.get("/product/productList")
    console.log(response.data.data)
    const data = response.data.data
    if (response.data.code == 200) {
        products.value = data
    }
}

const formatCurrency = (value) => {
    if (value)
        return value.toLocaleString('cn-CN', { style: 'currency', currency: 'CNY' });
    return;
};
const openNew = () => {
    product.value = {};
    submitted.value = false;
    imageName.value = "newImage";
    productDialog.value = true;
};
const hideDialog = () => {
    productDialog.value = false;
    submitted.value = false;
    imageName.value = "new";
};
const saveProduct = async () => {
    submitted.value = true;
    console.log(product.value)

    if ((!product.value.name || !product.value.category || !product.value.price || !product.value.quantity)) {
        console.log("gg");
        return;
    }
    const response = await axios.post("/product/addProduct", product.value)
    if (response.data.code == 200) {
        productDialog.value = false;
        product.value = {};
        toast.add({ severity: 'success', summary: 'success', detail: response.data.message, life: 3000 })
        getData();
        setTimeout(() => {
            location.reload();
        }, 1000);
    }

};
const editProduct = (prod) => {
    product.value = { ...prod };
    imageName.value = product.value.id;
    productDialog.value = true;
    console.log(product.value.id)
};
const confirmDeleteProduct = (prod) => {
    product.value = prod;
    deleteProductDialog.value = true;
};
const deleteProduct = async () => {
    console.log(product.value.id)
    const response = await axios.post(`/product/deleteProduct/${product.value.id}`)
    if (response.data.code == 200) {
        toast.add({ severity: 'success', summary: 'Successful', detail: response.data.message, life: 3000 });
        deleteProductDialog.value = false;
        getData();
    }
    /* products.value = products.value.filter(val => val.id !== product.value.id);
    deleteProductDialog.value = false;
    product.value = {}; */
};
const findIndexById = (id) => {
    let index = -1;
    for (let i = 0; i < products.value.length; i++) {
        if (products.value[i].id === id) {
            index = i;
            break;
        }
    }

    return index;
};
const createId = () => {
    let id = '';
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < 5; i++) {
        id += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return id;
}
const exportCSV = () => {
    dt.value.exportCSV();
};
const confirmDeleteSelected = () => {
    deleteProductsDialog.value = true;
};
const deleteSelectedProducts = async () => {
    const deleteProducts = products.value.filter(val => selectedProducts.value.includes(val));
    console.log(deleteProducts)
    const response = await axios.post("/product/deleteProduct", deleteProducts)
    if (response.data.code == 200) {
        deleteProductsDialog.value = false;
        selectedProducts.value = null;
        toast.add({ severity: '', summary: 'Successful', detail: 'Products Deleted', life: 3000 });
        setTimeout(() => {
            location.reload();
        }, 1000)
    }
};

const getStatusLabel = (status) => {
    switch (status) {
        case 'INSTOCK':
            return 'success';

        case 'LOWSTOCK':
            return 'warning';

        case 'OUTOFSTOCK':
            return 'danger';

        default:
            return null;
    }
};

</script>
